const WebSocket = require('ws');
 
// 初始化WebSocket服务器
const wss = new WebSocket.Server({ port: 8080 });
 
wss.on('connection', function connection(ws) {
  // 当客户端连接时，发送欢迎消息
  ws.send(JSON.stringify({ type: 'welcome' }));
 
  // 监听客户端发送的消息
  ws.on('message', function incoming(message) {
    console.log('received: %s', message);
 
    // 将接收到的消息广播到所有客户端
    wss.clients.forEach(function each(client) {
      if (client !== ws && client.readyState === WebSocket.OPEN) {
        client.send(message);
        ws.send(message);
      }
    });
  });
 
  // 当连接关闭时执行
  ws.on('close', function close() {
    console.log('disconnected');
  });
 
  // 当出现错误时执行
  ws.on('error', function error(e) {
    console.log('error: %s', e);
  });
});
 
console.log('WebSocket server is running on ws://localhost:8080');